/**
 * @author PRAVEEN KUMAR VERMA
 * 
 */

package com;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mail.SendMail;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.connection.jdbconnection;

public class StudentForm extends HttpServlet {
	private static final long serialVersionUID = 1L;

	static Connection conn = null;

	PreparedStatement pst = null;
	ResultSet rs = null;
	String sname;
	String fname;
	String dob;
	String address;
	String gender;
	String contact;
	String emailid;
	String course;
	String image;
	String issuedate;
	String batch;
	String validuntill;
	String student_id;
	String id;
	String date;
	String time;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		jdbconnection db = new jdbconnection();
		Statement st = db.jdbConnection();
		StudentForm form = new StudentForm();

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String path = getServletContext().getRealPath("photo");

		HttpSession session = request.getSession();
		/*
		 * issuedate=(String) request.getAttribute(issuedate);
		 * validuntill=(String) request.getAttribute(validuntill);
		 * 
		 * System.out.println(issuedate); System.out.println(validuntill);
		 */
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
		} else {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					String name = item.getFieldName();

					String value = item.getString();
					System.out.println(name + value);
					if (name.equals("sname")) {
						sname = value;
					}
					if (name.equals("fname")) {
						fname = value;
					}
					if (name.equals("dob")) {
						dob = value;
					}
					if (name.equals("gender")) {
						gender = value;
					}
					if (name.equals("address")) {
						address = value;
					}
					if (name.equals("contact")) {
						contact = value;
					}
					if (name.equals("emailid")) {
						emailid = value;
					}
					if (name.equals("course")) {
						course = value;
					}
					if (name.equals("batch")) {
						batch = value;
					}
					if (name.equals("issuedate")) {
						issuedate = value;

					}
					if (name.equals("validuntill")) {
						validuntill = value;

					}

				} else {
					try {
						String itemName = item.getName();
						String name[] = itemName.split("\\.");
						Random random = new Random();
						int z = random.nextInt(23000);
						String name1 = name[0] + z;
						image = name1 + "." + name[1];
						File savedFile = new File(path + "/" + image);
						image = "photo/" + image;
						item.write(savedFile);

						java.util.Date date1 = new java.util.Date();

						DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
						date = df.format(date1);
						Calendar cal = Calendar.getInstance();
						cal.getTime();
						SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
						System.out.println(sdf.format(cal.getTime()));
						time = sdf.format(cal.getTime());
						System.out.println("Time=" + time);

						ResultSet set = st
								.executeQuery("select student_id from studentform ");
						if (!set.next()) {
							student_id = "ST0000101";
						} else if (!set.next()) {
							student_id = "ST0000129";
						} else {
							set.last();
							String s = set.getString(1);
							System.out.println(s);
							set.previous();
							System.out.println(set.getString(1));
							String s2 = set.getString(1);
							long x = Integer.parseInt(s.substring(2));
							long y = Integer.parseInt(s2.substring(2));
							long temp = x * 2 - y + 9;
							student_id = "ST0000" + temp;
							id = student_id;
							System.out.println(id);
						}

					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String queryS = "Insert into studentform values('"
							+ student_id + "','" + sname + "','" + fname
							+ "','" + dob + "','" + gender + "','" + address
							+ "','" + contact + "','" + emailid + "','"
							+ course + "','" + image + "','" + batch + "','"
							+ issuedate + "','" + validuntill + "','" + date
							+ "','" + time + "')";

					System.out.println(queryS);
					System.out.println(student_id);
					System.out.println(id);
					try {
						int a = st.executeUpdate(queryS);
						session.setAttribute("id", student_id);
						session.setAttribute("sname", sname);

						if (a == 1) {
							String sub = "Registered Successfully in Hi rel info genisis ";
							String msg = "Dear "
									+ sname
									+ ", Thank you for being the student of the Hi-rel info genisis your Enrollment Number is :"
									+ student_id
									+ ", For any kind of information please contact on 7503390877";
							SendMail mail = new SendMail();
							mail.sendMessageToMail(emailid, sub, msg);
							// HttpSession session=request.getSession();

							System.out
									.println("Student Detail Submit Successfully.");

							request.getRequestDispatcher("studentEnrol.jsp")
									.forward(request, response);

						}
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		}

	}

}
